package com.jt.assistant.ui

import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.GsonUtils
import com.google.gson.reflect.TypeToken
import com.jt.assistant.R
import com.jt.assistant.adapter.ScanAdapter
import com.jt.assistant.adapter.WaybillListAdapter
import com.jt.assistant.base.GlobalConfig
import com.jt.assistant.bean.ScanCarton
import com.jt.assistant.bean.ScanDataBean
import com.jt.assistant.bean.Waybill
import com.jt.assistant.viewmodel.HomeViewModel
import com.tencent.mmkv.MMKV
import com.yzp.mvvmlibrary.base.BaseActivity
import kotlinx.android.synthetic.main.activity_waybill_state.*
import java.util.ArrayList

/**
 * 运单列表
 */
class WaybillStateActivity : BaseActivity<HomeViewModel>() {

    private val mAdapter by lazy {
        WaybillListAdapter(
            ArrayList<Waybill>()
        )
    }
    private var mScanData: ScanDataBean? = null
    private val mScanCartonList = ArrayList<ScanCarton>()

    override fun layoutId(): Int = R.layout.activity_waybill_state

    override fun initView(savedInstanceState: Bundle?) {
        with(rv_waybill) {
            layoutManager = LinearLayoutManager(context)
            adapter = mAdapter
        }
    }

    override fun initData() {

        MMKV.defaultMMKV()
            .getString(GlobalConfig.SCAN_DATA, "").let {
                mScanData = GsonUtils.fromJson(
                    it, ScanDataBean::class.java
                )
            }

        MMKV.defaultMMKV()
            .getString(GlobalConfig.SCAN_CARTON_LIST, "").let {
                mScanCartonList.addAll(
                    GsonUtils.fromJson<ArrayList<ScanCarton>>(
                        it, object : TypeToken<ArrayList<ScanCarton>>() {}.type
                    )
                )
            }
        mAdapter.updateData(mScanData!!, mScanCartonList)
        log(mScanData!!)
        log(mScanCartonList)
    }

    override fun initListener() {
        mAdapter.setOnItemClickListener { adapter, view, position ->
             val scanCartonList = ArrayList<ScanCarton>()
            mScanCartonList.forEach {
                if (!it.hasScan&&it.channelOrderNo == mScanData!!.waybillList[position].channelOrderNo){
                    scanCartonList.add(it)
                }
            }

            startActivity(Intent(this@WaybillStateActivity, CartonStateActivity::class.java).apply {
                MMKV.defaultMMKV().putString(GlobalConfig.SCAN_CARTON_LIST, GsonUtils.toJson(scanCartonList))
            })

        }

    }

}